package com.wfh.aiagent.tools;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.wfh.aiagent.constant.FileConstant;
import com.wfh.aiagent.manager.ObsManager;
import jakarta.annotation.Resource;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/28 9:12
 * @Version 1.0
 */
@Component
public class PDFGenerationTool {

    @Resource
    private ObsManager obsManager;

    @Tool(description = "Generate a PDF file with given content", returnDirect = true)
    public String generatePDF(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Content to be included in the PDF") String content) {
        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + fileName;
        String upload;
        try {
            // 创建目录
            FileUtil.mkdir(fileDir);
            // 创建 PdfWriter 和 PdfDocument 对象
            try (PdfWriter writer = new PdfWriter(filePath);
                 PdfDocument pdf = new PdfDocument(writer);
                 Document document = new Document(pdf)) {
                // 自定义字体（需要人工下载字体文件到特定目录）
                String fontPath = Paths.get("src/main/resources/ttf/fzmw.ttf")
                        .toAbsolutePath().toString();
                PdfFont font = PdfFontFactory.createFont(fontPath,
                        PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
                // 使用内建的亚洲字体
                // PdfFont font = PdfFontFactory.createFont("sun-extA", "UniGB-UCS2-H");
                document.setFont(font);
                // 创建段落
                Paragraph paragraph = new Paragraph(content);
                // 添加段落并关闭文档
                document.add(paragraph);
            }
            // 上传到对象存储
            File file = FileUtil.file(filePath);
            upload = obsManager.upload(file, "pdf/" + fileName);
            return "PDF generated successfully to local path: " + filePath
                    +"And remote file path is:" + upload;
        } catch (IOException e) {
            return "Error generating PDF: " + e.getMessage();
        }
    }
}
